package com.leyou.order.utils;

import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayConfigImpl;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public class PayHelper {


    @Autowired
    private WXPayConfigImpl config;
    @Autowired
    private WXPay wxPay;

    public  String getPayUrl(String desc,long orderId,long totalFee){
        //准备请求参数
        Map<String, String> data = new HashMap<>();
        data.put("body", desc);
        data.put("out_trade_no", String.valueOf(orderId));
        data.put("total_fee", String.valueOf(totalFee));
        data.put("spbill_create_ip", "123.12.12.123");
        data.put("notify_url", config.getNotifyUrl());
        data.put("trade_type", config.getPayType());  // 此处指定为扫码支付



        try {
            //发起请求
            Map<String, String> resp = wxPay.unifiedOrder(data);
            //校验业务标示
            checkResultCode(resp);
            //取出支付连接地址并返回
            String url = resp.get("code_url");
            if (StringUtils.isBlank(url)){
                throw new RuntimeException("【微信支付】下单支付连接为空");
            }
            return url;
        } catch (Exception e) {
            //统一下单失败
            log.error("【支付助手】统一下单失败，失败原因：{}",e.getMessage(),e);
            throw new LyException(ExceptionEnum.WX_PAY_ERROR);
        }
    }

    private void checkResultCode(Map<String, String> resp) {
        //判断业务执行结果

        if (WXPayConstants.FAIL.equals(resp.get("result_code"))){
            //下单业务失败
            log.error("【支付助手】统一下单失败，错误码：{}，错误原因：{}",
                    resp.get("err_code"),resp.get("err_code_des"));
            throw new LyException(ExceptionEnum.WX_PAY_ERROR);
        }
    }

    public void checkSignature(Map<String,String> data){
        try {
            boolean boo1 = WXPayUtil.isSignatureValid(data, config.getKey(), WXPayConstants.SignType.MD5);
            boolean boo2 = WXPayUtil.isSignatureValid(data, config.getKey(), WXPayConstants.SignType.HMACSHA256);
            if (!boo1 && !boo2){
                throw new RuntimeException();
            }
        } catch (Exception e) {
            log.error("【支付助手】签名校验失败！");
            throw new RuntimeException("非法签名，别瞎搞，不然就报警了",e);
        }

    }
}
